﻿namespace Raven
{
    public class PrecisionTimer
    {
        internal Fix currentTime => _frameCount * _frameTime;
        internal int frameCount => _frameCount;

        private int _frameCount;
        private Fix _lastTime = 0;
        private Fix _totalTime;
        private Fix _frameTime;
        private Fix _fps;
        private IQueryTime _queryTime;
        private Fix _timeScale = 1;

        public PrecisionTimer(Fix fps, IQueryTime queryTime)
        {
            _queryTime = queryTime;
            _fps = fps;
            _timeScale = 1;
            Start(_queryTime.GetTime());
        }

        private void Start(Fix queryTime)
        {
            _frameTime = Fix.One / _fps;
            _lastTime = queryTime;
            _totalTime = 0;
            _frameCount = 0;
        }

        public bool ReadyForNextFrame()
        {
            Fix current = _queryTime.GetTime();
            _totalTime += (current - _lastTime) * _timeScale;
            _lastTime = current;
            if (_totalTime >= _frameCount * _frameTime)
            {
                _frameCount++;
                return true;
            }

            return false;
        }

        public void SetTimerScale(Fix scale)
        {
            _timeScale = scale;
        }

        public Fix GetTimerScale()
        {
            return _timeScale;
        }
    }
}